var express = require('express');
var crypto = require('crypto');
const CryptoJS = require('crypto-js'); //引用AES源码js
var router = express.Router();
var mysql = require('mysql');

//实现本地链接
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'zxw68824',
    database: 'users'
});

router.post('/', function (req, res, next) {
    //设置允许前端跨域请求本接口
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");

    var par = paramAll(req);

    if (!checkOvertime(par.time)) { //时间戳超过当前时间戳两分钟即为超时，为了防止黑客抓包直接提交
        return res.send('时间戳超时');
    }

    var user = {
        account: par.account,
        password: par.password,
        time: par.time
    }

    var param = getSortObjByAsciiWithObj(user, 'zxw201905142059'); //和前端采用一致的签名sign加密方式

    if (param.sign == par.sign) { //如果加密签名和前端加密sign一致则验证成功
        try {
            var password = Decrypt(user.password);
            password = encryPassword(password);
            console.log(password);

            connection.connect(function (err) {
                if (err) {
                    console.error('error connecting:' + err.stack)
                }
            });
        
            connection.query('SELECT * FROM users where username = ?', [user.account], function (error, results, fields) {
                if (error) {
                    throw error;
                }else{
                    connection.end();
                    if(password == results[0].password){
                        return res.send({
                            status: 200,
                            account: user.account,
                            msg: '登录成功'
                        });
                    }else{
                        return res.send({
                            status: 201,
                            msg: '登录失败'
                        });
                    }
                }
            });
        } catch (e) {
            console.log(e);
        }

    } else { //否则验证失败
        console.log('签名认证成功!');
        return res.send({
            status: 200,
            msg: '签名验证失败'
        });
    }
});

//解密方法
function Decrypt(word) {
    const key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF"); //十六位十六进制数作为密钥
    const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412'); //十六位十六进制数作为密钥偏移量
    let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    let decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

var encryPassword = this.encryPassword = function (password) {
    password = 'tao1024' + password;
    var md5 = crypto.createHash('md5');
    md5.update(password);
    password = md5.digest('hex');
    return password;
};

var checkOvertime = this.checkOvertime = function (t) {
    var time = new Date().getTime();
    if (parseInt((time - t) / 1000) > 120) {
        return false;
    } else {
        return true;
    }
}

//返回拼接上sign的请求对象
function getSortObjByAsciiWithObj(obj, secret) {

    var sortArrStr = getSortStrByAsciiWithObj(obj); //组成按字母顺序排序的字符串

    var waitSecretStr = secret + sortArrStr + secret; //使用前后加secret的方式拼接待加密字符串   waitStr="ek93nkdkswWjfetkey=JF201811212112125phone=18605996973score=11time=1545449321396ek93nkdkswWjfet"
    // console.log(waitSecretStr);
    var md5 = crypto.createHash('md5');
    md5.update(waitSecretStr); //waitSign="c51951be9421b1dd93f9938555d71da5"
    var stringSign = md5.digest('hex');
    var sign = stringSign.toLocaleLowerCase(); //sign="c51951be9421b1dd  93f9938555d71da5"
    obj.sign = sign;
    return obj;
}

//构造按Ascii码顺序组成的字符串
function getSortStrByAsciiWithObj(obj) {
    var arr = [];
    for (var key in obj) {
        arr.push(key);
    }
    var sortArr = getsParaFromArr(arr); //返回按字母顺序排序的数组
    var sortArrStr = '';
    sortArr.forEach(function (key) {
        var item = {};
        item[key] = obj[key];
        sortArrStr += key + '=' + obj[key];
    });

    // console.log('sortArrStr = ' + sortArrStr);
    return sortArrStr; //str="key=JF201811212112125phone=18605996973score=11time=1545449321396"
}

//传入数组，返回按Ascii码排序的数组
function getsParaFromArr(sParaTemp) {
    var sPara = [];
    //除去数组中的空值和签名参数
    for (var i1 = 0; i1 < sParaTemp.length; i1++) {
        var value = sParaTemp[i1];
        if (value == null || value == "" || value == "sign") {
            continue;
        }
        sPara.push(value);
    }
    sPara = sPara.sort();
    return sPara;
}

var paramAll = this.paramAll = function (req) {
    var parameter = {};
    if (req.params) {
        for (var p in req.params) {
            parameter[p] = req.params[p];
        }
    }
    if (req.body) {
        for (var p in req.body) {
            parameter[p] = req.body[p];
        }
    }
    if (req.query) {
        for (var p in req.query) {
            parameter[p] = req.query[p];
        }
    }
    return parameter;
};

module.exports = router;